package cn.zc.curriculum.service.service.impl;


import cn.tools.common.enums.TestedFile;
import cn.tools.core.VO.PageVO;
import cn.tools.core.exception.BizException;
import cn.tools.core.utils.mybatis.PageUtil;
import cn.tools.dozer.config.DozerUtils;
import cn.zc.curriculum.entity.CurriculumVideo;
import cn.zc.curriculum.entity.Dto.CurriculumVideoDto;
import cn.zc.curriculum.entity.UploadFilePaths;
import cn.zc.curriculum.entity.VO.CurriculumVideoVO;
import cn.zc.curriculum.service.config.UploadConfig;
import cn.zc.curriculum.service.config.hander.VideoResourceHttpRequestHandler;
import cn.zc.curriculum.service.mapper.CurriculumVideoMapper;
import cn.zc.curriculum.service.service.CurriculumVideoService;
import cn.zc.curriculum.service.service.UploadFileService;
import cn.zc.curriculum.service.service.UploadFileServiceAsync;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author keno
 * @since 2022-02-14
 */
@Service
public class CurriculumVideoServiceImpl extends ServiceImpl<CurriculumVideoMapper, CurriculumVideo> implements CurriculumVideoService {
    @Resource
    private CurriculumVideoMapper curriculumVideoMapper;

    @Resource
    private UploadFileService uploadFileService;

    @Resource
    private UploadFileServiceAsync uploadFileServiceAsync;

    @Resource
    private UploadConfig uploadConfig;

    @Resource
    private DozerUtils dozerUtils;

    /**
     * 注入处理本地文件视频流的配置类
     */
    @Resource
    private VideoResourceHttpRequestHandler videoResourceHttpRequestHandler;

    /**
     * 上传视频
     * @param video
     * @return
     */
    @Override
    public CurriculumVideoVO uploadCurriculumVideo(MultipartFile video) {

        UploadFilePaths uploadFilePaths = uploadFileService.testedFile(video);
        for (String endName:uploadConfig.getVideoEnd()) {
            if (endName.equals(uploadFilePaths.getEndName().toLowerCase())) {

                try {

                    uploadFileService.uploadFileTestedCloud(video.getInputStream(), uploadFilePaths.getFileSavePath(), TestedFile.VIDEO);
                    uploadFileService.saveLocalTested(video.getInputStream(), uploadFilePaths.getFilePath(), uploadFilePaths.getLocalPath(), TestedFile.VIDEO);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                CurriculumVideoVO videoVO = new CurriculumVideoVO();
                //返回路径前，先检测配置文件是否开启保存
                if(uploadConfig.isVideoLocalSave()) {
                    videoVO.setVideoUrl(uploadFilePaths.getLocalPath());
                }
                if(uploadConfig.isVideoOssSave()) {
                    videoVO.setVideoUrl(uploadFilePaths.getOssSavePath());
                }
                if(uploadConfig.isVideoBlwsSave()) {
                    videoVO.setVideoBlwsUrl("");
                }
                    videoVO.setVideoSuffix(uploadFilePaths.getEndName());
                    videoVO.setVideoSize(video.getSize());
                return videoVO;
            }
        }

        throw new BizException("上传文件失败,不支持此类后缀：" + uploadFilePaths.getEndName());
    }


    /**
     * 删除视频
     * @param id
     */
    @Override
    public void deleteCurriculumVideo(String id) {
        CurriculumVideo videoInfo = getById(id);
        if(videoInfo == null){
            throw new BizException("在数据库未查找到视频数据");
        }
        if(videoInfo.getVideoOssUrl() != null) {
            uploadFileServiceAsync.deleteOssFile(videoInfo.getVideoOssUrl());
        }
        if(videoInfo.getVideoUrl() != null){
            uploadFileServiceAsync.deleteLocalFile(videoInfo.getVideoUrl());
        }
        //TODO 保利威视的接口还没写暂时不进行删除操作
        if(videoInfo.getVideoBlwsUrl() != null){

        }
        if(!removeById(id)){
            throw new BizException("删除失败");
        }
    }


    /**
     * 创建视频
     * @param curriculumVideoDto
     * @return
     */
    @Override
    public CurriculumVideoDto createCurriculumVideo(CurriculumVideoDto curriculumVideoDto) {
        CurriculumVideo video = dozerUtils.map(curriculumVideoDto, CurriculumVideo.class);
        if(!save(video)){
            throw new BizException("创建视频失败");
        }
        curriculumVideoDto.setId(video.getId());
        return curriculumVideoDto;
    }


    /**
     * 修改视频
     * @param curriculumVideoDto
     */
    @Override
    public void updateCurriculumVideo(CurriculumVideoDto curriculumVideoDto) {
        CurriculumVideo video = dozerUtils.map(curriculumVideoDto, CurriculumVideo.class);
        if(!updateById(video)){
            throw new BizException("修改视频失败");
        }
    }


    /**
     * 根据条件查询视频
     * @param pageVO
     * @param curriculumVideoDto
     * @return
     */
    @Override
    public List<CurriculumVideoDto> findCurriculumVideo(PageVO pageVO, CurriculumVideoDto curriculumVideoDto) {
        return curriculumVideoMapper.findCurriculumVideo(PageUtil.initPage(pageVO),curriculumVideoDto);
    }


    /**
     * 通过id获取本地文件视频流
     * @param request
     * @param response
     * @param videoId
     */
    @Override
    public void findVideoStream(HttpServletRequest request, HttpServletResponse response,String videoId) {
        CurriculumVideo videoInfo = getById(videoId);
        if(videoInfo.getVideoUrl() != null) {
            videoResourceHttpRequestHandler.path = videoInfo.getVideoUrl();
              response.setContentType("video/"+ videoInfo.getVideoSuffix());
            try {
                videoResourceHttpRequestHandler.handleRequest(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            throw new BizException("视频资源不存在，无法播放");
        }
    }
}
